package nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class GroupChatServer {
    public static final int PORT = 9999;
    private static Selector selector;
    private static ServerSocketChannel serverSocketChannel;
    public GroupChatServer() {
        // 执行初始化操作
        try {
            selector = Selector.open();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
            // 设置非阻塞模式
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("服务器启动成功...");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听通道发送消息
     */
    public void listen() {
        try {
            while (true) {
                int select = selector.select();
                if (select > 0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        if (selectionKey.isAcceptable()) {
                            SocketChannel channel = serverSocketChannel.accept();
                            channel.configureBlocking(false);
                            channel.register(selector, SelectionKey.OP_READ);
                        }
                        if (selectionKey.isReadable()) {
                            readData(selectionKey);
                        }
                        iterator.remove();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取客户端发送数据
     * @param selectionKey
     * @throws IOException
     */
    private void readData(SelectionKey selectionKey) throws IOException {
        SocketChannel channel = (SocketChannel)selectionKey.channel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int read = channel.read(byteBuffer);
        if (read > 0) {
            String msg = new String(byteBuffer.array(), 0, read);
            System.out.println(channel.getRemoteAddress() + " 发送消息: " + msg);
            // 将消息转发给其他客户端
            pushMessage(selector.keys(), channel, msg);
        } else {
            System.out.println("未接收到数据");
        }
    }

    /**
     * 推送消息给其他客户端
     * @param keys
     * @param self
     * @param message
     */
    public void pushMessage(Set<SelectionKey> keys, SocketChannel self, String message) throws IOException {
        Iterator<SelectionKey> iterator = keys.iterator();
        while (iterator.hasNext()) {
            SelectionKey selectionKey = iterator.next();
            SelectableChannel channel = selectionKey.channel();
            if (channel instanceof SocketChannel && channel != self) {
                ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBytes());
                ((SocketChannel) channel).write(byteBuffer);
            }
        }
    }

    public static void main(String[] args) {
        GroupChatServer server = new GroupChatServer();
        server.listen();
    }
}
